﻿using AutoWelding.Models;
using AutoWelding.Utils;
using K4os.Compression.LZ4;
using log4net.Repository.Hierarchy;
using MySql.Data.MySqlClient;
using Mysqlx.Crud;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace AutoWelding.DAL
{
    public class LogsDAL
    {
        /// <summary>
        /// 获取所有日志数据，返回List
        /// </summary>
        /// <returns></returns>
        public List<LogsModel> GetLogsList(string logLevel, DateTime startTime, DateTime endTime)
        {
            List<LogsModel> logsList = new List<LogsModel>();

            // SELECT* FROM logs_info WHERE log_level = 'DeBug' AND log_time BETWEEN '2025-01-01 00:00:00' AND '2025-12-31 23:59:59' ORDER BY id DESC
            string sql = "SELECT * FROM logs_info";
            List<MySqlParameter> parameters = new List<MySqlParameter>();

            if (logLevel != "All")
            {
                sql += " WHERE log_level = @loglevel";
                parameters.Add(new MySqlParameter("@loglevel", logLevel));
                sql += " AND log_time BETWEEN @startTime AND @endTime";
            }
            else
                sql += " WHERE log_time BETWEEN @startTime AND @endTime";
            sql += " ORDER BY id DESC"; // 倒序

            try
            {
                parameters.Add(new MySqlParameter("@startTime", startTime));
                parameters.Add(new MySqlParameter("@endTime", endTime));

                // List对象转换为数组对象
                DataTable dt = MysqlHelp.ExecuteQuery(sql, parameters.ToArray());
                // 遍历数据表(DataTable)中的所有行(DataRow) 并将每一行的数据转换为LogsModel对象 然后添加到logsList集合中
                foreach (DataRow row in dt.Rows)
                {
                    logsList.Add(new LogsModel
                    {
                        // 映射属性
                        id = Convert.ToInt32(row["id"]), // 非空
                        log_level = row["log_level"].ToString(),
                        log_message = row["log_message"].ToString(),
                        logger = row["logger"].ToString(),
                        log_time = Convert.ToDateTime(row["log_time"]) // 非空
                    });
                }
                return logsList;
            }
            catch (Exception ex)
            {
                // 数据访问层 记录日志 重新抛出异常
                // throw new Exception("获取日志数据失败: " + ex.Message);
                throw;
            }
        }


    }
}
